﻿<?
require_once "inc.init.php";
define(GALLERY_PREFIX, "gallery_");

// THE OBJ:
$obj = new proyectos(); // <---- Change this !!!
$obj-> setDbLink($dbLink);

// GETTING:
$obj->get( $_GET[$obj->_dbIndex] );
$isNew = $obj->getID()?FALSE:TRUE;

// MESSENGER
$messenger = new Messenger();

if($_GET['action']=='save_images')
{
    $photoAlbum = new FileManagerPhotoAlbum($module->photoAttr);
    $photoAlbum->setDBLink($dbLink);
    if(!($obj->photo_albumID && $photoAlbum->get($obj->photo_albumID))) 
    {
        $photoAlbum->userID_modified = $obj->userID_modified;
        $photoAlbum->create();
        $obj->photo_albumID = $photoAlbum->getID();
        $obj->update();
    }
    $photoAlbum->uploadMultiple($_FILES, GALLERY_PREFIX);
    $photoAlbum->removeMultiple($_POST);
}

// SAVING:
if ($_POST['action'] == 'save') 
{
    if ($user->isEnabledTo("write", $module->id))
    {
        if($_POST['sponsor'] == 'otro' && $_POST['nombre_sponsor'] != '')
        {
            $_POST['sponsor'] = $_POST['nombre_sponsor'];
            $obj->link_sponsor='';
        }
        
        $obj->set($_POST, true);
        $obj->active = ($_POST['active']=='Y')?'Y':'N';
        $obj->userID_modified = $user->getID();
        
        $validator = new DataObjectValidator();
        $validator->setFields(array('nombre', 'information', 'address', 'general_information'));
        $validator->doNotAllowEmptyFields = true;
        if (!$validator->validate($_POST)) $validator->addErrorsToMessenger($messenger);

        if(!$messenger->countMessages())
        {        
            if($obj->save())
            {
                // The imagenes:
                if ($module->images[get_class($obj)])
                {
                    $obj->loadImages();
                    foreach($module->images[get_class($obj)] AS $imgID => $imgConfig)
                    {
                        if ($_POST['del'.$imgID]) $obj->deleteImage($imgID);
                        $obj->updateImage($imgID, $_FILES[$imgID] );
                    }
                }
                $messenger->setMessageType(1);
                $messenger->addMessage("Changes saved successfully.");
            }
            else $messenger->addMessage("There was an internal error, please: retry.");
        }
    }
    else $messenger->addMessage($lang->translate("user_action_denied"));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?= $GLOBALS["website"]["name"] ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> 
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/bootstrap.css">
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/font-awesome.min.css">
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/plugin.css">
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/font.css" cache="false">
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/style.css">
    <script src="<?= $GLOBALS['CONF']['url']['js'] ?>/lib/prototype-min.js" type="text/javascript" language="javascript" charset="utf-8"></script>
    <?=jquery()?>
    <?=jqueryui()?>
    <script type="text/javascript">
        var $j = jQuery.noConflict();
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places,geometry" type="text/javascript"></script>
    <script language="JavaScript" type="text/javascript" src="<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/tiny_mce/tinymce.min.js"></script>
    <script src="<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/scriptaculous/scriptaculous.js?load=effects,controls,dragdrop" type="text/javascript" language="javascript" charset="utf-8"></script>
    <!-- Needs to be seperate script tags! -->
    <script language="JavaScript" type="text/javascript">
        tinymce.baseURL = "<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/tiny_mce";
        tinyMCE.init({
            theme: 'modern',
            plugins: [
                "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars code fullscreen",
                "insertdatetime media nonbreaking save table contextmenu directionality",
                "emoticons template paste textcolor"
            ],
            toolbar1: "undo redo | forecolor | bold italic | link",
            theme_advanced_styles : "Texto 1=texto;Texto 2=epb3;Texto 3=titulares",
            content_css : "<?= $GLOBALS["CONF"]["url"]["root"] ?>/admin/css/inc.content.forms.css",
            mode : "specific_textareas",
            forced_root_block : "",
            editor_selector : "mceEditor"
        });
    </script>
    <style>
    .left{
        float:left;
    }
    .right{
        float:right;
    }
    .end{
        clear:both;
    }
    </style>
</head>
<body>
    <section id="content">
      <?
        if($messenger)
        {
            $messages = $messenger->getArMessages();
            if(count($messages))
            {
                $html='<div id="respuesta_estado_orden" class="alert alert-success fade in"><div class="left">';
                foreach($messages as $key => $value)
                {
                    $html.=$value."<br>";
                }
                $html.='</div>
                            <div class="right">
                                <button class="btn_close_messeger close" data-dismiss="alert" type="button">×</button>
                            </div>
                            <div class="end"></div>
                        </div>';
            }
            echo $html;
        }
        ?>
        <section class="main padder">
            <div class="row">
                <br>
                <!-- .breadcrumb -->
                <ul class="breadcrumb">
                    <li><a href="."><?= $module->name ?></a></li>
                    <li class="active"><?
                        if ($obj->getID())
                        {
                            ?><a href="#"><?= $obj->nombre ?></a><? 
                        }
                        else
                        {
                            echo ucfirst($lang->translate("adding")) ." ". strtolower($module->unit);
                        }
                        ?>
                    </li>
                </ul>
                <!-- / .breadcrumb -->
                <?
                    if ($obj->getID())
                    {
                        ?>
                        <div class="col-sm-12">
                            <section class="toolbar clearfix m-t-large m-b">
                                <a class="btn btn-primary btn-circle active" href="gallery.php?<?=$obj->_dbIndex."=".$obj->getID()?>"><i class="icon-picture"></i>Gallery</a>
                            </section>
                        </div>
                        <?
                    }
                ?>
                <div class="col-sm-12">
                    <section class="panel">
                        <div class="panel-body">
                            <form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Nombre</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="nombre" id="name" placeholder="Nombre" class="form-control" value="<?= $obj->nombre?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Nota Título</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="nota_titulo" placeholder="Título" class="form-control" value="<?= $obj->nota_titulo?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Nota Descripción</label>
                                    <div class="col-lg-8">
                                        <textarea placeholder="Descripción" rows="5" class="form-control mceEditor" name="nota_descripcion"><?=$obj->nota_descripcion?></textarea>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Video Embed</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="html_video_embed" placeholder="Video" class="form-control" value="<?= htmlentities($obj->html_video_embed)?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Imagen proyecto</label>
                                    <div class="col-lg-8">
                                    <? $obj->printImageHTML('hexa') ?>
                                    <br>
                                    <input type="file" name="hexa" id="hexa">
                                    <input name="delhexa" type="checkbox" id="delhexa" value="1"/> Borrar
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Dirección (Hexágono)</label>
                                    <div class="col-lg-6">
                                        <input type="text" name="direccion_visible" class="form-control" value="<?=$obj->direccion_visible?>">
                                    </div>
                                </div>                                
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Dirección</label>
                                    <div class="col-lg-6">
                                        <div class="input-group">
                                            <input type="text" name="direccion" class="form-control" id="inputDireccion" value="<?=$obj->direccion?>">
                                            <span class="input-group-btn">
                                                <button class="btn login" type="button" id="graficar">Go! <i class="icon-map-marker icon-white"></i></button>
                                            </span>
                                            <input type="hidden" name="lat" id="lat" value="<?=$obj->lat?>">
                                            <input type="hidden" name="lng" id="lng" value="<?=$obj->lng?>">
                                        </div>
                                        <div id="canvas-map" style="margin-top:5px;width:500px;height:250px;display:hidden;">&nbsp;</div>
                                    </div>
                                </div>
                                <div class="form-group">    
                                    <div class="line line-dashed m-t-large"></div>
                                    <label class="col-lg-3 control-label">Sponsor</label>
                                    <div class="col-lg-8">
                                        <select name="sponsor" id="sponsor">
                                            <option value="">-- Seleccionar --</option>
                                            <option value="ideame" <?= $obj->sponsor == 'ideame' ? 'selected="selected"' : '' ?>>Ideame</option>
                                            <option value="otro" <?= $obj->sponsor != 'ideame' ? 'selected="selected"' : '' ?>>Otro</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group ideame" <?= $obj->sponsor != 'ideame' ? 'style="display:none"' : ''?>>
                                    <label class="col-lg-3 control-label" >Link proyecto</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="link_sponsor" placeholder="Link Proyecto"  class="form-control" value="<?= $obj->link_sponsor?>">
                                    </div>
                                </div>
                                <div class="form-group otro_sponsor" <?= $obj->sponsor == 'ideame' ? 'style="display:none"' : ''?>>
                                    <label class="col-lg-3 control-label">Nombre Sponsor</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="nombre_sponsor" placeholder="Nombre Sponsor"  class="form-control" value="<?= $obj->sponsor?>">
                                    </div>
                                </div>
                                <div class="form-group otro_sponsor" <?= $obj->sponsor == 'ideame' ? 'style="display:none"' : ''?>>
                                    <label class="col-lg-3 control-label">Foto Sponsor</label>
                                    <div class="col-lg-8">
                                        <? $obj->printImageHTMLThumb('sponsor') ?>
                                        <? $obj->printImageHTML('sponsor') ?>
                                        <br>
                                        <input type="file" name="<?= 'sponsor' ?>" id="<?= 'sponsor' ?>">
                                        <input name="del<?= 'sponsor' ?>" type="checkbox" id="del<?= 'sponsor' ?>" value="1"/> Borrar
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="line line-dashed m-t-large"></div>
                                    <label class="col-lg-3 control-label">KM recorridos</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="km" placeholder="KM Recorridos"  class="form-control" value="<?= $obj->km?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Alcance de niños involucrados</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="ninos_involucrados" placeholder="Alcance de niños involucrados"  class="form-control" value="<?= $obj->ninos_involucrados?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Pelotas Repartidas</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="pelotas_repartidas" placeholder="Pelotas repartidas"  class="form-control" value="<?= $obj->pelotas_repartidas?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Paises Recorridos</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="paises_recorridos" placeholder="Paises Recorridos"  class="form-control" value="<?= $obj->paises_recorridos ?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Acciones / Elementos Deportivos</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="acciones_elementos_deportivos" placeholder="Acciones / Elementos Deportivos"  class="form-control" value="<?= $obj->acciones_elementos_deportivos ?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Personas de la comunidad involucradas</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="personas_involucradas" placeholder="Personas de la comunidad involucradas"  class="form-control" value="<?= $obj->personas_involucradas ?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="line line-dashed m-t-large"></div>
                                    <label class="col-lg-3 control-label">HTML meta title</label>
                                    <div class="col-lg-8">
                                        <div class="input-group">
                                            <input type="text" name="html_meta_title" placeholder="Title" id="html_meta_title" class="form-control" value="<?= $obj->html_meta_title?>">
                                            <span class="input-group-btn">
                                                <button class="btn login" type="button" onClick="javascript:$j('#html_meta_title').val($j('#name').val());void(0);">Copiar Nombre</button>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">HTML meta description</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="html_meta_description" placeholder="Descripcion" class="form-control" value="<?= $obj->html_meta_description?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">HTML meta keywords</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="html_meta_keywords" placeholder="Pelotas, Escobar, futbol" class="form-control" value="<?= $obj->html_meta_keywords?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="line line-dashed m-t-large"></div>
                                    <label class="col-lg-3 control-label">Activo</label>
                                    <div class="col-lg-8">
                                        <input type="checkbox" <?= $obj->active == 'Y' ? "checked" : '' ?> name="active" value="Y">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-lg-9 col-lg-offset-3">
                                        <button type="submit" class="btn btn-primary">Save</button> o 
                                        <a href="."><span> [Cancel]</span></a>
                                    </div>
                                </div>
                                <input type="hidden" name="action" value="save">
                            </form>
                            <!--<div class="well m-t">
                                <div class="row">
                                    <div class="col-xs-12">
                                        <strong>Info de sistema </strong><br>
                                        <?= $module->unit ?> id: <?= $obj->getID() ?><br>
                                    </div>
                                    <div class="col-xs-6">
                                        Fecha de creaci&oacute;n : <?= $obj->date_created ?><br>
                                        Fecha &uacute;ltimo cambio: <?= $obj->date_modified ?></br>
                                    </div>
                                    <div class="col-xs-6">
                                        Usuario que cre&oacute;: <?= $obj->userCreated ?></br>
                                        Usuario que modific&oacute;: <?= $obj->userModified ?></br>
                                    </div>
                                </div>
                            </div>-->
                        </div>
                    </section>
                </div>
            </div>
        </section>
    </section>
<script>
var options = {};
var origin = document.getElementById('inputDireccion');
// add the map to the map placeholder
<?
    if($obj->lat != '' && $obj->lng != '' && $obj->direccion!='')
    {
        ?>
            var LatinAmerica = new google.maps.LatLng(<?=$obj->lat?>,<?=$obj->lng?>);
            var zoomFirst = 13;
        <?
    }
    else
    {
        ?>
            var LatinAmerica = new google.maps.LatLng(-20.08525080,-59.47209040);
            var zoomFirst = 1;
        <?
    }
?>


var mapOptions = {
  zoom:zoomFirst,
  center: LatinAmerica,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  mapTypeControl: false
};

var map = new google.maps.Map(document.getElementById('canvas-map'), mapOptions);
var originAutocomplete = new google.maps.places.Autocomplete(origin, options);
function graficar()
{
    originPlace = originAutocomplete.getPlace();
    
    $j("#lat").val(originPlace.geometry.location.lat());
    $j("#lng").val(originPlace.geometry.location.lng());

    if (originPlace.geometry.viewport) {
      map.fitBounds(originPlace.geometry.viewport);
    } else {
      map.setCenter(originPlace.geometry.location);
      map.setZoom(13);
    }
    
    var marker = new google.maps.Marker({
      map: map
    });

    //console.log(originAutocomplete.getBounds());
    var image = new google.maps.MarkerImage(
            originPlace.icon, new google.maps.Size(71, 71),
            new google.maps.Point(0, 0), new google.maps.Point(17, 34),
            new google.maps.Size(35, 35));
    marker.setIcon(image);
    marker.setPosition(originPlace.geometry.location);

    var address = '';
    if (originPlace.address_components) {
          address = [
            (originPlace.address_components[0] &&
             originPlace.address_components[0].short_name || ''),
            (originPlace.address_components[1] &&
             originPlace.address_components[1].short_name || ''),
            (originPlace.address_components[2] &&
             originPlace.address_components[2].short_name || '')].join(' ');
        }
    $j('#canvas-map').show();
}

google.maps.event.addListener(originAutocomplete, 'place_changed', function() {
    originPlace = originAutocomplete.getPlace();
    $j("#lat").val(originPlace.geometry.location.lat());
    $j("#lng").val(originPlace.geometry.location.lng());
});
$j("#graficar").click(function(){graficar()});
<?
if($obj->lat != '' && $obj->lng != '' && $obj->direccion != '')
{
    ?>
    var marker = new google.maps.Marker({
      map: map
    });

    //console.log(originAutocomplete.getBounds());
    var image = new google.maps.MarkerImage(
            'http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png', new google.maps.Size(71, 71),
            new google.maps.Point(0, 0), new google.maps.Point(17, 34),
            new google.maps.Size(35, 35));
    marker.setIcon(image);
    marker.setPosition( new google.maps.LatLng(<?=$obj->lat?>, <?=$obj->lng?>));
    <?
}
?>
    $j(".btn_close_messeger").click(function(){
        $j("#respuesta_estado_orden").fadeOut("fast");
    });
    
    $j( "#sponsor" ).change(function() {
        if(this.value=='ideame')
        {
            $j('.otro_sponsor').hide();
            $j('.ideame').show();
        }
        else if(this.value=='otro')
        {
            $j('.ideame').hide();
            $j('.otro_sponsor').show();
        }
        else if(this.value=='')
        {
            $j('.otro_sponsor').hide();
            $j('.ideame').hide();
        }
    });
</script>
</body>
</html>
